package com.example.acclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.*;
import com.google.gson.Gson;

public class MainActivity extends Activity implements LocationListener {

	private static final String TAG = "Ajou Conqueror";
	private GoogleMap map;
	private LocationManager locationManager;
	private String provider;
	Polyline polyline = null;
	Marker marker;

	private final String HOST = "10.168.10.116";
	private final int PORT = 8080;
	private final String PATH_GET = "/ACserver-war/webresources/location";
	private final String PATH_POST = "/ACserver-war/webresources/location";
	private final String LOGIN_POST = "/ACserver-war/webresources/user";

	private String path;
	private String MIME = "text/plain";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		provider = LocationManager.GPS_PROVIDER;
		Location lastLocation = locationManager.getLastKnownLocation(provider);

		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
				.getMap();

		if (map != null) {
			// this overrides the initial map type we defined in XML
			map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

			// shows how shapes are used
		}
		marker = map.addMarker(new MarkerOptions().position(
				new LatLng(lastLocation.getLatitude(), lastLocation
						.getLongitude())).icon(
				BitmapDescriptorFactory
						.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));

		if (lastLocation != null)
			onLocationChanged(lastLocation);
	}

	@Override
	protected void onResume() {
		locationManager.requestLocationUpdates(provider, 5000, 10, this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		locationManager.removeUpdates(this);
		super.onPause();
	}

	public void onLocationChanged(Location location) {
		LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
		addShapes(loc);
		CameraPosition cameraPosition;
		cameraPosition = new CameraPosition.Builder().target(loc).zoom(15)
				.build();
		map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
		marker.setPosition(loc);

		customLocation loca = new customLocation(location.getLatitude(),
				location.getLongitude());
		path = PATH_POST;
		AsyncCreate ac = new AsyncCreate();
		ac.execute(loca);
		path = LOGIN_POST;
		AsyncLogin al = new AsyncLogin();
		al.execute("admin", "admin", "false");

	}

	private void addShapes(LatLng ll) {

		// create polyline options that contain points of the line segments
		// that form rectangle.

		if (polyline == null) {
			PolylineOptions polylineOptions = new PolylineOptions();
			polylineOptions.add(ll).color(Color.RED);
			polyline = map.addPolyline(polylineOptions);
		} else {
			List<LatLng> points = polyline.getPoints();
			points.add(ll);
			polyline.setPoints(points);
		}
		// Add a polyline.

	}

	private class AsyncLogin extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			boolean result = false;
			String name = params[0];
			String pwd = params[1];
			Boolean team = Boolean.parseBoolean(params[2]);

			List<NameValuePair> list = new ArrayList<NameValuePair>();
			list.add(new BasicNameValuePair("name", name));
			list.add(new BasicNameValuePair("pwd", pwd));
			list.add(new BasicNameValuePair("team", team.toString()));

			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(path);

			// set the MIME type for POST message body.
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");

			StringEntity se;
			try {
				se = new UrlEncodedFormEntity(list);
				post.setEntity(se);

				HttpResponse response = client.execute(target, post);
				HttpEntity resEntity = response.getEntity();

				if (resEntity != null) {
					String resultstr = EntityUtils.toString(resEntity);
					Log.d(TAG, resultstr);
					if (resultstr.trim().equals("LOGIN_SUCCESS")) {
						result = true;
					} else if (resultstr.trim().equals("ADMIN_LOGIN_SUCCESS")) { // TEAM A, TEAM B
						result = true;
					} else {
						result = false;
					}
				} else {
					result = false;
				}

				Log.d(TAG, response.getStatusLine().getStatusCode() + "");
				if (response.getStatusLine().getStatusCode() == 204
						|| response.getStatusLine().getStatusCode() == 200)
					result = true;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				Toast.makeText(getApplicationContext(), "Success!",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), "Failed!",
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

	}

	private class AsyncCreate extends AsyncTask<customLocation, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(customLocation... params) {
			boolean result = false;

			// create() method of the web service needs a Person object as input
			// String quote = addQuote.getText().toString().trim();
			String loc = LocToJSON(params[0]);

			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(path);

			// set the MIME type for POST message body.
			post.setHeader("Content-Type", MIME);

			StringEntity se;
			try {
				se = new StringEntity(loc, HTTP.UTF_8);
				post.setEntity(se);
				HttpResponse response = client.execute(target, post);
				Log.d(TAG, response.getStatusLine().getStatusCode() + "");
				if (response.getStatusLine().getStatusCode() == 204
						|| response.getStatusLine().getStatusCode() == 200)
					result = true;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				Toast.makeText(getApplicationContext(), "Success!",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), "Failed!",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	private customLocation JSONToLoc(String json) {
		Gson gson = new Gson();
		customLocation cl = gson.fromJson(json, customLocation.class);
		return cl;
	}

	private String LocToJSON(customLocation cl) {
		Gson gson = new Gson();
		String json = gson.toJson(cl);
		return json;
	}
}
